package com.asiainfo.dacp.datastash.worker.executor.adapter.datax.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Maps;

public class ConfigUtils {
	static Logger LOG = LoggerFactory.getLogger(ConfigUtils.class);  

	public static Map<String, String> propsToStringMap(Properties props) {
		Map<String, String> result = Maps.newHashMap();
		for (Map.Entry<Object, Object> entry : props.entrySet())
			result.put(entry.getKey().toString(), entry.getValue().toString());
		return result;
	}
	
	public static String getCfg(String key) throws FileNotFoundException, IOException{
		String jobResource = ConfigUtils.class.getClassLoader().getResource(".").getFile();
		jobResource = jobResource + File.separator + "config.properties";
		Map<String, String> propsToStringMap = propsToStringMap(loadProps(jobResource)); 
		return propsToStringMap.get(key);
	}

	public static Properties loadProps(String filename) throws IOException, FileNotFoundException {
		Properties props = new Properties();
		InputStream propStream = new FileInputStream(filename);
		props.load(propStream);
		return props;
	}

	public static Map<String, Object> propertiesWithPrefix(Map<String, ?> properties, String prefix,
			boolean recursion) {
		String newPrefix = prefix;
		if (prefix.length() > 0 && prefix.trim().charAt(prefix.length() - 1) != '.') {
			newPrefix += ".";
		}
		Map<String, Object> result = Maps.newHashMap();
		for (Map.Entry<String, ?> entry : properties.entrySet()) {
			if (entry.getKey().startsWith(newPrefix) && entry.getKey().length() > newPrefix.length()) {
				String key = entry.getKey().substring(newPrefix.length());
				if (!recursion && key.contains(".")) {
					continue;
				}
				result.put(key, entry.getValue());
			}
		}
		return result;
	}

	public static Map<String, Object> propertiesWithPrefix(Map<String, ?> properties, String prefix) {
		return propertiesWithPrefix(properties, prefix, true);
	}
}
